/**
 * gridUtil.js
 * @Author: lij
 * @CreateDate：2016年6月12日13:34:40
 * @Version 1.0
 * Copyright (C) 2016 NRIET
 * 格点数据bytes解析(bytes数组中的数据位置只适用特定文件,如有差异,各自新建更改)
 */
var gridUtil;
if (!window.gridUtil) {
	gridUtil={};
}else{
	//throw new Error("gridUtil has already existed!");
}
//var combileByteArr= function(arr){
//	var len = arr.length;
//	
//	var res = 0;
//	
//	for (var i = 0; i < len; i++){
//		res = ((0x00000000 | arr[i]) << (8 * i)) | res;
//	}
//			
//	return res;
//};
gridUtil.convertRadarData=function(resp){
	var rst = {};
	var a = new Uint8Array(resp);
	//rst.LongitudeValue = combileByteArr(new Uint8Array([a[164],a[165],a[166],a[167]]));
	// 年
	rst.year =  new Int16Array(new Uint8Array([a[66],a[67]]).buffer)[0]; 
	// 月
	rst.month =  new Int16Array(new Uint8Array([a[68],a[69]]).buffer)[0]; 
	// 日
	rst.day =  new Int16Array(new Uint8Array([a[70],a[71]]).buffer)[0]; 
	// 时
	rst.hour =  new Int16Array(new Uint8Array([a[72],a[73]]).buffer)[0]; 
	// 分
	rst.minute =  new Int16Array(new Uint8Array([a[74],a[75]]).buffer)[0]; 
	//经向格点数
	rst.nx = new Int16Array(new Uint8Array([a[78],a[79]]).buffer)[0];// 也可以combileByteArr(new Uint8Array([a[78],a[79]]));
	//纬向格点数
	rst.ny = new Int16Array(new Uint8Array([a[80],a[81]]).buffer)[0];
	//高度层数
	rst.nz = new Int16Array(new Uint8Array([a[82],a[83]]).buffer)[0];
	//起始经度
	rst.startLon = new Float32Array(new Uint8Array([a[88],a[89],a[90],a[91]]).buffer)[0];
	//起始纬度
	rst.startLat = new Float32Array(new Uint8Array([a[92],a[93],a[94],a[95]]).buffer)[0];
	//结束经度
	rst.endLon = 2*(new Float32Array(new Uint8Array([a[96],a[97],a[98],a[99]]).buffer)[0])-rst.startLon;
	//结束纬度
	rst.endLat = 2*(new Float32Array(new Uint8Array([a[100],a[101],a[102],a[103]]).buffer)[0])-rst.startLat;
	//经度方向分辨率
	rst.dx=new Float32Array(new Uint8Array([a[104],a[105],a[106],a[107]]).buffer)[0];
	//纬度方向分辨率
	rst.dy=new Float32Array(new Uint8Array([a[108],a[109],a[110],a[111]]).buffer)[0];
	//数据
	rst.data=[];
	var index = 111+912+1;
	for(var i=0;i<rst.nz;i++){
		for (var j = rst.ny-1; j >=0; j--) {
			for (var k = 0; k < rst.nx; k++) {
				rst.data.push((a[index]-66)/2);
				index++;
			}
		}
	}
	return rst;
};

gridUtil.convertGridData1=function(resp){
	var rst = {};
	var grid = {};
	var a = new Uint8Array(resp);
	//rst.LongitudeValue = combileByteArr(new Uint8Array([a[164],a[165],a[166],a[167]]));
	// 年
	grid.year =  new Int16Array(new Uint8Array([a[66],a[67]]).buffer)[0]; 
	// 月
	grid.month =  new Int16Array(new Uint8Array([a[68],a[69]]).buffer)[0]; 
	// 日
	grid.day =  new Int16Array(new Uint8Array([a[70],a[71]]).buffer)[0]; 
	// 时
	grid.hour =  new Int16Array(new Uint8Array([a[72],a[73]]).buffer)[0]; 
	// 分
	grid.minute =  new Int16Array(new Uint8Array([a[74],a[75]]).buffer)[0]; 
	//经向格点数
	grid.nx = new Int16Array(new Uint8Array([a[78],a[79]]).buffer)[0];// 也可以combileByteArr(new Uint8Array([a[78],a[79]]));
	//纬向格点数
	grid.ny = new Int16Array(new Uint8Array([a[80],a[81]]).buffer)[0];
	//高度层数
	grid.nz = new Int16Array(new Uint8Array([a[82],a[83]]).buffer)[0];
	//起始经度
	grid.startLon = new Float32Array(new Uint8Array([a[88],a[89],a[90],a[91]]).buffer)[0];
	//起始纬度
	grid.endLat = new Float32Array(new Uint8Array([a[92],a[93],a[94],a[95]]).buffer)[0];
	//结束经度
	grid.endLon = 2*(new Float32Array(new Uint8Array([a[96],a[97],a[98],a[99]]).buffer)[0])-grid.startLon;
	//结束纬度
	grid.startLat = 2*(new Float32Array(new Uint8Array([a[100],a[101],a[102],a[103]]).buffer)[0])-grid.startLat;
	//经度方向分辨率
	grid.dx=new Float32Array(new Uint8Array([a[104],a[105],a[106],a[107]]).buffer)[0];
	//纬度方向分辨率
	grid.dy=new Float32Array(new Uint8Array([a[108],a[109],a[110],a[111]]).buffer)[0];
	grid.time=grid.year+"-"
	+(grid.month<10?"0"+grid.month:grid.month)+"-"
	+(grid.day<10?"0"+grid.day:grid.day)+" "
	+(grid.hour<10?"0"+grid.hour:grid.hour)+":"
	+(grid.minute<10?"0"+grid.minute:grid.minute);
	//数据
	rst.data=[];
	var index = 111+912+1;
	for(var i=0;i<rst.nz;i++){
		for (var j = rst.ny-1; j >=0; j--) {
			for (var k = 0; k < rst.nx; k++) {
				rst.data.push((a[index]-66)/2);
				index++;
			}
		}
	}
	rst.grid = grid;
	return rst;
};

gridUtil.convertGridData2=function(resp){
	var rst = {};
	var grid = {};
	var a = new Uint8Array(resp);
	//rst.LongitudeValue = combileByteArr(new Uint8Array([a[164],a[165],a[166],a[167]]));
	// 年
	grid.year =  new Int16Array(new Uint8Array([a[48],a[49]]).buffer)[0]; 
	// 月
	grid.month =  new Int16Array(new Uint8Array([a[50],a[51]]).buffer)[0]; 
	// 日
	grid.day =  new Int16Array(new Uint8Array([a[52],a[53]]).buffer)[0]; 
	// 时
	grid.hour =  new Int16Array(new Uint8Array([a[54],a[55]]).buffer)[0]; 
	// 分
	grid.minute =  new Int16Array(new Uint8Array([a[56],a[57]]).buffer)[0]; 

	var lf6 =  new Int16Array(new Uint8Array([a[20],a[21]]).buffer)[0];// 记录长度
	var lf7 = new Int16Array(new Uint8Array([a[22],a[23]]).buffer)[0];// 文件头占用记录数
	var lf8 = new Int16Array(new Uint8Array([a[24],a[25]]).buffer)[0];// 产品数 据占用记录数
	
	var ls7 =  new Int16Array(new Uint8Array([a[58],a[59]]).buffer)[0];// 通道号
	var ls14 =  new Int16Array(new Uint8Array([a[72],a[73]]).buffer)[0];// 北纬
	var ls15 =  new Int16Array(new Uint8Array([a[74],a[75]]).buffer)[0];// 南纬
	var ls16 =  new Int16Array(new Uint8Array([a[76],a[77]]).buffer)[0];// 西经
	var ls17 =  new Int16Array(new Uint8Array([a[78],a[79]]).buffer)[0];// 东经
	
	// 定标数据
	var std = [];
	var bb=102;
	for (var i = 0; i < 1024; i++) {
		std[i] =(new Int16Array(new Uint8Array([a[bb],a[bb+1]]).buffer)[0]) & 0xffff;// 年 bb.getShort() & 0xffff; // 亮度温值不为负 
		bb=bb+2;
	}

	rst.grid = grid;
	rst.data=[]; 
	var st=lf6 * lf7;
	var data=new Array();
	for (var i = lf8 - 1; i >= 0; i--) {
		data[i]=new Array();
		for (var j = 0; j < lf6; j++) {
			var idx =a[st] & 0xff;// & 0xff;
			if (4 == ls7) {
				idx /= 4;
			} else {
				idx *= 4;
			}
			idx=parseInt(idx);
//			rst.data.push(std[idx] / 100);
			data[i][j]=std[idx] / 100;
			st++;
		}
	}
	//颠倒调正
	for (var i = 0; i< lf8 ; i++) {
		for (var j = 0; j < lf6; j++) {
			rst.data.push(data[i][j]);
		}
	}
	

	var startLon = ls16 / 100;
	var endLon = ls17 / 100;
	var startLat = ls14 / 100;
	var endLat = ls15 / 100;
	var dx = (endLon - startLon) / lf6;
	var dy = (endLat - startLat) / lf8;

	//经向格点数
	grid.nx = lf6;// 也可以combileByteArr(new Uint8Array([a[78],a[79]]));

	//纬向格点数
	grid.ny = lf8;
	//纬向格点数
	grid.dx = dx;
	grid.dy = dy;
	grid.startLon = startLon;
	grid.endLon = endLon;
	grid.startLat = startLat;
	grid.endLat = endLat;
//	rst.coef=0;
//	rst.endIsoline=0;
	rst.invalid=0;
//	rst.isolineDist=0;
//	rst.startIsoline=0;
//	rst.thick=0;
	grid.time=grid.year+"-"
	+(grid.month<10?"0"+grid.month:grid.month)+"-"
	+(grid.day<10?"0"+grid.day:grid.day)+" "
	+(grid.hour<10?"0"+grid.hour:grid.hour)+":"
	+(grid.minute<10?"0"+grid.minute:grid.minute);
	var d;
	var arr = grid.time.split(" ");
	var arr1 = arr[0].split("-");
	var arr2 = arr[1].split(":");
	d = new Date(arr1[0], arr1[1] - 1, arr1[2], arr2[0], arr2[1], "00");
	d.setHours(d.getHours()+8);
	grid.time=d.toString("yyyy-MM-dd hh:mm");


	return rst;
};

gridUtil.convertGridData3=function(resp){
	var rst = {};
	var grid = {};
	
	rst.data=[]; 
	
	if(resp.byteLength == 0)
		return rst;
	var a = new DataView(resp);
	var pos = 0;
	//rst.LongitudeValue = combileByteArr(new Uint8Array([a[164],a[165],a[166],a[167]]));
	// 年
	grid.year =  a.getInt16(pos, false);
	pos += Int16Array.BYTES_PER_ELEMENT; 
	// 月
	grid.month =  a.getInt8(pos, false);
	pos += Int8Array.BYTES_PER_ELEMENT; 
	// 日
	grid.day =   a.getInt8(pos, false);
	pos += Int8Array.BYTES_PER_ELEMENT; 
	// 时
	grid.hour =   a.getInt8(pos, false);
	pos += Int8Array.BYTES_PER_ELEMENT; 
	// 分
	grid.minute =   a.getInt8(pos, false);
	pos += Int8Array.BYTES_PER_ELEMENT; 
	//通道号
	var tdh =   a.getInt8(pos, false);
	pos += Int8Array.BYTES_PER_ELEMENT; 
	
	grid.endLat = a.getFloat32(pos, false);
	pos += Float32Array.BYTES_PER_ELEMENT;
	grid.startLat = a.getFloat32(pos, false);
	pos += Float32Array.BYTES_PER_ELEMENT;
	grid.startLon = a.getFloat32(pos, false);
	pos += Float32Array.BYTES_PER_ELEMENT;
	grid.endLon = a.getFloat32(pos, false);
	pos += Float32Array.BYTES_PER_ELEMENT;

	//经向格点数
	grid.ny =  a.getInt32(pos, false);
	pos += Int32Array.BYTES_PER_ELEMENT;
	//纬向格点数
	grid.nx =  a.getInt32(pos, false);
	pos += Int32Array.BYTES_PER_ELEMENT;
	
	grid.dx = (grid.endLon - grid.startLon) / grid.nx;
	grid.dy = Math.abs((grid.endLat - grid.startLat) / grid.ny);
	// 定标数据
	var std = [];
	for (var i = 0; i < 1024; i++) {
		std[i] = a.getUint16(pos, false);
		pos += Uint16Array.BYTES_PER_ELEMENT;
	}
	var dataSize=grid.ny*grid.nx;
	for (var i = 0; i< dataSize ; i++) {
		var idx =a.getUint8(pos, false);
		pos += Uint8Array.BYTES_PER_ELEMENT;
		if (4 == tdh && 255 == idx) {
			rst.data.push(-1);
		} else if (4 == tdh) {
			idx = parseInt(idx);
			rst.data.push(std[idx]/100);
		} else if (0 == idx) {
			rst.data.push(-1);
		} else {
			idx *= 4;
			rst.data.push(std[idx]/100);
		}
	}
	rst.invalid=-1;
	
	grid.time=grid.year+"-"
	+(grid.month<10?"0"+grid.month:grid.month)+"-"
	+(grid.day<10?"0"+grid.day:grid.day)+" "
	+(grid.hour<10?"0"+grid.hour:grid.hour)+":"
	+(grid.minute<10?"0"+grid.minute:grid.minute);
	
	
	var d;
	var arr = grid.time.split(" ");
	var arr1 = arr[0].split("-");
	var arr2 = arr[1].split(":");
	d = new Date(arr1[0], arr1[1] - 1, arr1[2], arr2[0], arr2[1], "00");
	d.setHours(d.getHours()+8);
	grid.time=d.toString("yyyy-MM-dd hh:mm");
	
	
	rst.grid = grid;
	return rst;
};

//卫星葵花
gridUtil.convertGridData4=function(resp){
	var rst = {};
	var grid = {};
	
	rst.data=[]; 
	
	if(resp.byteLength == 0)
		return rst;
	var a = new DataView(resp);
	var pos = 0;
	//rst.LongitudeValue = combileByteArr(new Uint8Array([a[164],a[165],a[166],a[167]]));
	// 年
	grid.year =  a.getInt16(pos, false);
	pos += Int16Array.BYTES_PER_ELEMENT; 
	// 月
	grid.month =  a.getInt8(pos, false);
	pos += Int8Array.BYTES_PER_ELEMENT; 
	// 日
	grid.day =   a.getInt8(pos, false);
	pos += Int8Array.BYTES_PER_ELEMENT; 
	// 时
	grid.hour =   a.getInt8(pos, false);
	pos += Int8Array.BYTES_PER_ELEMENT; 
	// 分
	grid.minute =   a.getInt8(pos, false);
	pos += Int8Array.BYTES_PER_ELEMENT; 
	//通道号
	var tdh =   a.getInt8(pos, false);
	pos += Int8Array.BYTES_PER_ELEMENT; 
	
	grid.endLat = a.getFloat32(pos, false);
	pos += Float32Array.BYTES_PER_ELEMENT;
	grid.startLat = a.getFloat32(pos, false);
	pos += Float32Array.BYTES_PER_ELEMENT;
	grid.startLon = a.getFloat32(pos, false);
	pos += Float32Array.BYTES_PER_ELEMENT;
	grid.endLon = a.getFloat32(pos, false);
	pos += Float32Array.BYTES_PER_ELEMENT;

	//经向格点数
	grid.ny =  a.getInt32(pos, false);
	pos += Int32Array.BYTES_PER_ELEMENT;
	//纬向格点数
	grid.nx =  a.getInt32(pos, false);
	pos += Int32Array.BYTES_PER_ELEMENT;
	
	grid.dx = (grid.endLon - grid.startLon) / grid.nx;
	grid.dy = Math.abs((grid.endLat - grid.startLat) / grid.ny);
	
	debugger;
	// 定标数据
	/*var std = [];
	for (var i = 0; i < 1024; i++) {
		std[i] = a.getUint16(pos, false);
		pos += Uint16Array.BYTES_PER_ELEMENT;
	}*/
	var dataSize=grid.ny*grid.nx;
	for (var i = 0; i< dataSize ; i++) {
		var idx =a.getInt8(pos, false);
		idx = idx & 0xff;
		pos += Int8Array.BYTES_PER_ELEMENT;
		if (255 == idx) {
			idx = 9999;
		} else if (4 != tdh){
			idx = idx + 100;
		}
		rst.data.push(idx);
		/*if (4 == tdh && 255 == idx) {
			rst.data.push(-1);
		} else if (4 == tdh) {
			idx /= 4;
			idx = parseInt(idx);
			rst.data.push(idx/100);
		} else if (0 == idx) {
			rst.data.push(-1);
		} else {
			idx *= 4;
			rst.data.push(idx/100);
		}*/
	}
	rst.invalid=9999;
	
	grid.time=grid.year+"-"
	+(grid.month<10?"0"+grid.month:grid.month)+"-"
	+(grid.day<10?"0"+grid.day:grid.day)+" "
	+(grid.hour<10?"0"+grid.hour:grid.hour)+":"
	+(grid.minute<10?"0"+grid.minute:grid.minute);

	var d;
	var arr = grid.time.split(" ");
	var arr1 = arr[0].split("-");
	var arr2 = arr[1].split(":");
	d = new Date(arr1[0], arr1[1] - 1, arr1[2], arr2[0], arr2[1], "00");
	d.setHours(d.getHours()+8);
	grid.time=d.toString("yyyy-MM-dd hh:mm");
	
	rst.grid = grid;
	return rst;
};

/**
 * 查询格点数据
 * queryParam：参数（element：要素Id（必须），mode：gis展示用（必须））
 * url：请求路径
 * proType：产品类型（调用不同解析方法用）
 * recallFn：回调函数
 */
gridUtil.queryGridData=function(queryParam,url,proType,recallFn){
	var pStr = '';
	for (var key in queryParam) {
		pStr += "&"+key+"="+queryParam[key];	
	}
	if(pStr.length>0){
		pStr = pStr.substring(1);
	}
	var xhr = new XMLHttpRequest();
	xhr.open('post',window.contextPath +url,true);
	xhr.responseType='arraybuffer';
	xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xhr.onload=function(e){
		var result=null;
		switch(proType){
			case'autosatellite':
				result = gridUtil.convertGridData3(this.response);
				break;
			case'satellite':
				result = gridUtil.convertGridData3(this.response);
				break;
			case'satelliteKH':
				result = gridUtil.convertGridData4(this.response);
				break;
			case 'radar':
				result = gridUtil.convertGridData1(this.response);
				break;
				//TODO
		} 
		
		if(result != null){
			result.flag=true;
			if (queryParam.mode) {
				result.mode=queryParam.mode.split(",");	
			}
			if (queryParam.element) {
				result.element = queryParam.element;
			}
		}
		if (recallFn) {
			recallFn(result);
		}
	};
	xhr.send(pStr);
};

/**
 * 创建等值线
 * @param {*} data 格点数据
 * @param {*} layerId 图层id
 * @param {*} levels 等值线的间隔
 */
gridUtil.createIsoline = function(data, layerId, levels, cutRings) {
	var rawInfo = G.ParseRaw(data);
	var row = rawInfo.rangeObj.nRows;
	var coloum = rawInfo.rangeObj.nCols;
	let zvalues = rawInfo.data; //格点值数组(从左上角开始的一维数组)
	var matrix = NinePointsSmoothing.prototype.transformToMatrix(zvalues, row, coloum);
	matrix = NinePointsSmoothing.prototype.smoothWithTimes(matrix, row, coloum, null, null, 10);
	zvalues = NinePointsSmoothing.prototype.transformToValues(matrix, row, coloum);

	let geoExtent = [rawInfo.rangeObj.xmin, rawInfo.rangeObj.ymin, rawInfo.rangeObj.xmax, rawInfo.rangeObj.ymax]; //格网对应的地理范围
	let symbol = new G.GLPolylineSymbol(1, "rgba(0,0,0,1)", 1, 1, 0); //默认等值线样式
	let labelOptions = {
		fillStyle: "rgba(255,0,0,1)", //标注颜色
		font: "14px 微软雅黑", //标注字体
		gap: 400, //标注间隙
		textWidthRatio: 0.4, //当标注字体长度与线条长度占比大于该值时，绘制标注
		rangeObj: {
			lineCut: true,
			cutRings: cutRings || [[[]]]  //裁剪范围
		}
	};
	//创建等值线图层
	let canvasLayer = GIS.Layer.IsolineLayerHelper.createIsolineLayer(GLMap, layerId, zvalues, row, coloum, levels, geoExtent, symbol, labelOptions, 3, null, null, true);
	//把等值线图层添加到map中
	GLMap.addLayer(canvasLayer);
}



